import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token'),
    isAuthenticated: !!localStorage.getItem('token')
  }),

  getters: {
    userInfo: (state) => state.user,
    isLoggedIn: (state) => state.isAuthenticated,
    userRole: (state) => state.user?.role || 'guest'
  },

  actions: {
    async login(username, password) {
      try {
        // 模拟登录验证
        const users = {
          'admin': { password: 'admin123', role: 'admin', name: '系统管理员' },
          'teacher': { password: 'teacher123', role: 'teacher', name: '教师' },
          'student': { password: 'student123', role: 'student', name: '学生' }
        }

        const user = users[username]
        if (user && user.password === password) {
          // 模拟生成token
          const token = 'mock-jwt-token-' + Date.now()
          
          this.user = {
            username,
            name: user.name,
            role: user.role
          }
          this.token = token
          this.isAuthenticated = true

          // 保存到localStorage
          localStorage.setItem('token', token)
          localStorage.setItem('user', JSON.stringify(this.user))

          return true
        }
        return false
      } catch (error) {
        console.error('登录失败:', error)
        return false
      }
    },

    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },

    // 初始化认证状态（页面刷新时）
    initAuth() {
      const token = localStorage.getItem('token')
      const user = localStorage.getItem('user')
      
      if (token && user) {
        this.token = token
        this.user = JSON.parse(user)
        this.isAuthenticated = true
      }
    },

    // 检查权限
    hasPermission(permission) {
      if (!this.user) return false
      
      const permissions = {
        admin: ['read', 'write', 'delete', 'manage'],
        teacher: ['read', 'write'],
        student: ['read']
      }
      
      const userPermissions = permissions[this.user.role] || []
      return userPermissions.includes(permission)
    }
  }
}) 